package cedar.sentinel.GWT.server;

import java.io.IOException;

import cedar.sentinel.GWT.client.TCPClient;
import cedar.sentinel.GWT.client.SentinelService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class SentinelServiceImpl extends RemoteServiceServlet implements SentinelService 
{  
  public static String DEFAULT_ADDR = "localhost";
  public static int DEFAULT_PORT = 4800;
  
  TCPClient pythonConnection;
  
  public SentinelServiceImpl()
  {
    //TODO loop to try again on secondary port
    try
    {
      pythonConnection = new TCPClient(DEFAULT_ADDR, DEFAULT_PORT);
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
  
	public String sentinelServer(String input) throws IllegalArgumentException
	{
	  if(input.charAt(0) == 's')
	  {
	    pythonConnection.toggleState();
	    return "Toggled state.";
	  }
	  if(input.charAt(0) == 'q')
	  {
	    pythonConnection.quit();
	    return "Quitting";
	  }
	  else
	  {
		int ID = Integer.valueOf(input);
  	  
  	    try
        {
          pythonConnection.sendToServer(ID);
        }
        catch (IOException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      return "Forwarded: " + ID + " to Python.";
	  }
	}
}
